import datetime
import json
import os
import sys

import boto3
import requests

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config import *


def run():
    emr = boto3.client("emr",
                       aws_access_key_id=FORMAL_S3_CONFIG['access_key'],
                       aws_secret_access_key=FORMAL_S3_CONFIG['secret_key'],
                       region_name=FORMAL_S3_CONFIG['region_name'])
    response = emr.list_clusters(ClusterStates=['STARTING', 'BOOTSTRAPPING', 'RUNNING', 'WAITING'])
    emrs = []
    for cluster in response['Clusters']:
        instances = emr.list_instances(
            ClusterId=cluster['Id']
        )
        ins_types = []
        for instance in instances['Instances']:
            ins_types.append(instance['InstanceType'])
        j = {'names': cluster['Name'], 'instances': ins_types,
             'start_time': str(cluster['Status']['Timeline']['CreationDateTime'])[0:19]+'+UTC'}
        emrs.append(j)
    print(json.dumps(emrs))

    time_after = datetime.datetime.now() - datetime.timedelta(days=300)
    sage = boto3.client('sagemaker',
                        aws_access_key_id=FORMAL_S3_CONFIG['access_key'],
                        aws_secret_access_key=FORMAL_S3_CONFIG['secret_key'],
                        region_name=FORMAL_S3_CONFIG['region_name'])

    studios = []
    domains = sage.list_domains(MaxResults=100)
    for domain in domains['Domains']:
        domain_id = domain['DomainId']
        domain_name = domain['DomainName']
        apps = sage.list_apps(DomainIdEquals=domain_id)
        for app in apps['Apps']:
            if app['AppType'] == 'KernelGateway' and app['Status'] == 'InService':
                app_name = app['AppName']
                start_time = str(app['CreationTime'])[0:19]+'+UTC'
                profile_name = app['UserProfileName']
                studios.append(
                    {'domain': domain_name, 'name': app_name, 'profile': profile_name, 'start_time': start_time})

    notes = []
    note_resp = sage.list_notebook_instances(LastModifiedTimeAfter=time_after, MaxResults=100)
    for note in note_resp['NotebookInstances']:
        if note['NotebookInstanceStatus'] == 'InService' or note['NotebookInstanceStatus'] == 'Pending':
            name = note['NotebookInstanceName']
            ins = note['InstanceType']
            start_time = str(note['LastModifiedTime'])[0:19]+'+UTC'
            notes.append({'name': name, 'instance': ins, 'start_time': start_time})

    ends = []
    end_resp = sage.list_endpoints(LastModifiedTimeAfter=time_after, MaxResults=100)
    for end in end_resp['Endpoints']:
        if end['EndpointStatus'] == 'InService' or end['EndpointStatus'] == 'Creating' or end[
            'EndpointStatus'] == 'Updating':
            name = end['EndpointName']
            start_time = str(end['LastModifiedTime'])[0:19]+'+UTC'
            ends.append({'name': name, 'start_time': start_time})

    jobs = []
    job_resp = sage.list_processing_jobs(LastModifiedTimeAfter=time_after, MaxResults=100)
    for job in job_resp['ProcessingJobSummaries']:
        if job['ProcessingJobStatus'] == 'InProgress':
            name = job['ProcessingJobName']
            start_time = str(job['LastModifiedTime'])[0:19]+'+UTC'
            jobs.append({'name': name, 'start_time': start_time})

    if len(emrs) == 0 and len(jobs) == 0 and len(ends) == 0 and len(notes) == 0 and len(studios) == 0:
        return
    sages = {'处理作业': jobs, '终端节点': ends, '笔记本': notes, 'Studio': studios}
    send(emrs, sages)


def send(emrs, sages):
    qywx_robot_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6084bd2e-4aaf-4c9e-8c04-3b48ba0fae20"
    send_url = qywx_robot_url
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        content = f'# AWS监控：<font color=\"warning\">正在运行的服务,如没有程序运行请手动关闭</font>'
        content = content + f'\n ## <font color=\"warning\">EMR:</font>'
        for emr in emrs:
            content = content + f"\n>  #### -集群名: {emr['names']}"
            content = content + f"\n <font color=\"comment\">   -实例类型: {str(emr['instances'])}</font> "
            content = content + f"\n <font color=\"comment\">   -启动时间:{emr['start_time']}</font> "

        for service, apps in sages.items():
            content = content + f'\n'
            content = content + f'\n'
            content = content + f'\n ### <font color=\"warning\">SageMaker-{service}:</font>'
            for app in apps:
                if service == 'Studio':
                    content = content + f"\n> #### -Domain: {app['domain']}"
                    content = content + f"\n> <font color=\"comment\">   Studio: {app['name']}</font>  "
                    content = content + f"\n> <font color=\"comment\">   Profile: {app['profile']}</font>  "
                    content = content + f"\n> <font color=\"comment\">   启动时间: {app['start_time']}</font>   "
                elif service == '笔记本':
                    content = content + f"\n> #### -笔记本: {app['name']}"
                    content = content + f"\n> <font color=\"comment\">   实例: {app['instance']}</font>  "
                    content = content + f"\n> <font color=\"comment\">   启动时间: {app['start_time']}</font>   "
                elif service == '终端节点':
                    content = content + f"\n> #### -终端节点: {app['name']}"
                    content = content + f"\n> <font color=\"comment\">   启动时间: {app['start_time']}</font>   "
                else:
                    content = content + f"\n> #### -处理作业: {app['name']}"
                    content = content + f"\n> <font color=\"comment\">   启动时间: {app['start_time']}</font>   "
        msg = {
            "msgtype": 'markdown',
            "markdown": {'content': content}
        }
    except Exception as e:
        print(str(e))
        msg = {
            "msgtype": 'text',
            "text": {'content': f'执行错误,{str(map)}'}
        }
    print(msg)
    response = requests.post(url=send_url, data=json.dumps(msg), headers=headers)
    print(map)
    print(response)
    print('已发送消息到企业微信')


# 空调mqtt数据超过阈值设备通知
if __name__ == '__main__':
    run()
